document.addEventListener('DOMContentLoaded', function() {
    const foodItemsContainer = document.getElementById('foodItems');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const cartBtn = document.getElementById('cartBtn');
    const cartModal = document.getElementById('cartModal');
    const closeCart = document.getElementsByClassName('close')[0];
    const cartItemsContainer = document.getElementById('cartItems');
    const cartTotal = document.getElementById('cartTotal');
    const checkoutBtn = document.getElementById('checkoutBtn');
    const logoutBtn = document.getElementById('logoutBtn');
    const feedbackModal = document.getElementById('feedbackModal');
    const feedbackIcon = document.getElementById('feedbackIcon');
    const feedbackTitle = document.getElementById('feedbackTitle');
    const feedbackMessage = document.getElementById('feedbackMessage');
    const feedbackConfirmBtn = document.getElementById('feedbackConfirmBtn');
    
    // 菜品数据
    let foodItems = [];
    
    // 从localStorage加载购物车数据
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    
    // 从后端API获取菜品数据
    function fetchFoodItems() {
        fetch('http://localhost:5000/api/foods')
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取菜品数据失败');
                }
                return response.json();
            })
            .then(data => {
                foodItems = data.map(item => ({
                    id: item.food_id,
                    name: item.food_name,
                    price: item.price,
                    image: item.image_path || '../images/default_food.jpg',
                    description: item.description,
                    category: item.category,
                    stock: item.stock
                }));
                displayFoodItems(foodItems);
            })
            .catch(error => {
                console.error('获取菜品数据错误：', error);
                showFeedback('error', '获取失败', '获取菜品数据失败，请刷新页面重试');
            });
    }
    
    // 显示菜品列表
    function displayFoodItems(items) {
        foodItemsContainer.innerHTML = '';
        
        items.forEach(item => {
            const foodItem = document.createElement('div');
            foodItem.className = 'food-item';
            
            foodItem.innerHTML = `
                <img src="${item.image}" alt="${item.name}" class="food-image">
                <div class="food-name">${item.name}</div>
                <div class="food-price">¥${parseFloat(item.price).toFixed(2)}</div>
                <button class="add-to-cart" data-id="${item.id}">加入购物车</button>
            `;
            
            foodItemsContainer.appendChild(foodItem);
        });
        
        // 添加购物车点击事件
        document.querySelectorAll('.add-to-cart').forEach(button => {
            button.addEventListener('click', addToCart);
        });
    }
    
    // 显示反馈模态框
    function showFeedback(type, title, message) {
        // 设置图标类型
        feedbackIcon.className = 'feedback-icon ' + type;
        
        // 设置图标内容
        if (type === 'success') {
            feedbackIcon.textContent = '✓';
        } else if (type === 'error') {
            feedbackIcon.textContent = '✗';
        } else {
            feedbackIcon.textContent = 'i';
        }
        
        // 设置标题和消息
        feedbackTitle.textContent = title;
        feedbackMessage.textContent = message;
        
        // 显示模态框
        feedbackModal.style.display = 'block';
    }
    
    // 添加到购物车
    function addToCart(event) {
        const foodId = parseInt(event.target.getAttribute('data-id'));
        const food = foodItems.find(item => item.id === foodId);
        
        if (food) {
            const existingItem = cart.find(item => item.id === foodId);
            
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({ ...food, quantity: 1 });
            }
            
            updateCart();
            showFeedback('success', '添加成功', `${food.name} 已添加到购物车`);
        }
    }
    
    // 更新购物车
    function updateCart() {
        cartItemsContainer.innerHTML = '';
        let total = 0;
        
        cart.forEach(item => {
            const itemTotal = parseFloat(item.price) * item.quantity;
            total += itemTotal;
            
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';
            
            cartItem.innerHTML = `
                <div class="cart-item-details">
                    <div>${item.name}</div>
                    <div>¥${parseFloat(item.price).toFixed(2)} x ${item.quantity}</div>
                </div>
                <div class="cart-item-price">¥${itemTotal.toFixed(2)}</div>
            `;
            
            cartItemsContainer.appendChild(cartItem);
        });
        
        cartTotal.textContent = total.toFixed(2);
        
        // 更新购物车按钮上的数量
        cartBtn.textContent = `购物车(${cart.length})`;
        
        // 保存购物车数据到localStorage
        localStorage.setItem('cart', JSON.stringify(cart));
    }
    
    // 搜索功能
    function searchFoods() {
        const searchTerm = searchInput.value.toLowerCase();
        const filteredFoods = foodItems.filter(item => 
            item.name.toLowerCase().includes(searchTerm)
        );
        
        displayFoodItems(filteredFoods);
    }
    
    // 事件监听
    searchBtn.addEventListener('click', searchFoods);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchFoods();
        }
    });
    
    // 反馈模态框确认按钮事件
    feedbackConfirmBtn.addEventListener('click', function() {
        feedbackModal.style.display = 'none';
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === feedbackModal) {
            feedbackModal.style.display = 'none';
        }
    });
    
    cartBtn.addEventListener('click', function() {
        // 重新从localStorage加载购物车数据
        cart = JSON.parse(localStorage.getItem('cart')) || [];
        updateCart();
        cartModal.style.display = 'block';
    });
    
    closeCart.addEventListener('click', function() {
        cartModal.style.display = 'none';
    });
    
    window.addEventListener('click', function(event) {
        if (event.target === cartModal) {
            cartModal.style.display = 'none';
        }
    });
    
    checkoutBtn.addEventListener('click', function() {
        if (cart.length === 0) {
            showFeedback('error', '购物车为空', '请先添加菜品');
            return;
        }
        
        // 保存购物车数据到localStorage
        localStorage.setItem('cart', JSON.stringify(cart));
        
        // 跳转到订单确认页面
        window.location.href = 'order_confirm.html';
    });
    
    logoutBtn.addEventListener('click', function() {
        // 清除用户信息
        localStorage.removeItem('user');
        localStorage.removeItem('cart');
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    });
    
    // 添加查看订单按钮点击事件
    const userInfoDiv = document.querySelector('.user-info');
    if (userInfoDiv) {
        // 检查是否已存在查看订单按钮
        if (!document.getElementById('viewOrdersBtn')) {
            const viewOrdersBtn = document.createElement('button');
            viewOrdersBtn.id = 'viewOrdersBtn';
            viewOrdersBtn.className = 'btn-orders';
            viewOrdersBtn.textContent = '我的订单';
            userInfoDiv.insertBefore(viewOrdersBtn, userInfoDiv.firstChild);
            
            viewOrdersBtn.addEventListener('click', function() {
                // 跳转到订单查询页面
                window.location.href = 'student_orders.html';
            });
        }
    }
    
    // 初始化页面
    fetchFoodItems();
    
    // 更新购物车按钮显示
    cartBtn.textContent = `购物车(${cart.length})`;
    
    // 获取用户信息
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('username').textContent = `欢迎，${user.username}`;
    }
});